<?php

function check_ewus ($username, $password, $pac_pesel){
    
    $params = array(
    'credentials' => array(
    array('name' => 'domain', 'value' => array('stringValue' => '07')),
    array('name' => 'login', 'value' => array('stringValue' => $username))
    ),
    'password' => $password);
    try { 
    $clientAuth = new SoapClient('https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl', array('trace' => true));
    $clientAuth->__soapCall('login', array($params), null, null, $loginHeaders);
    
    $date = date('Y-m-d\TH:i:s.BP'); 
    $xml = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:com="http://xml.kamsoft.pl/ws/common" xmlns:brok="http://xml.kamsoft.pl/ws/broker">
    <soapenv:Header>
    <com:session id="' . $loginHeaders['session']->id . '" xmlns:ns1="http://xml.kamsoft.pl/ws/common"/>
    <com:authToken id="' . $loginHeaders['authToken']->id . '" xmlns:ns1="http://xml.kamsoft.pl/ws/common"/>
    </soapenv:Header>
    <soapenv:Body>
    <brok:executeService>
    <com:location>
    <com:namespace>nfz.gov.pl/ws/broker/cwu</com:namespace>
    <com:localname>checkCWU</com:localname>
    <com:version>2.0</com:version>
    </com:location>
    <brok:date>'.$date.'</brok:date>
    <brok:payload>
    <brok:textload>
    <ewus:status_cwu_pyt xmlns:ewus="https://ewus.nfz.gov.pl/ws/broker/ewus/status_cwu/v2">
    <ewus:numer_pesel>'.$pac_pesel.'</ewus:numer_pesel>
    <ewus:system_swiad nazwa="eWUS" wersja="2.0"/>
    </ewus:status_cwu_pyt>
    </brok:textload>
    </brok:payload>
    </brok:executeService>
    </soapenv:Body>
    </soapenv:Envelope>';
     
    $clientBroker = new SoapClient('https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/ServiceBroker?wsdl', array('trace' => true, 'exceptions' => true));
    $r = $clientBroker->__doRequest($xml, 'https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/ServiceBroker', 'executeService', SOAP_1_1);

    $doc = new DOMDocument();
    $doc->loadXML($r);
    
    $blad = $doc->getElementsByTagName('faultstring')->item(0);
    if ($blad<>'') {
	return $blad->nodeValue;
	}
    else {    
    $match = $doc->getElementsByTagName('status_cwu_odp');
    $foundXML = $doc->saveXML($match->item(0));	
    $xpath = new DOMXpath($doc);
    $xpath->registerNamespace('odp','https://ewus.nfz.gov.pl/ws/broker/ewus/status_cwu/v2');
    $ewus_odp['nr_potw'] = $xpath->query("//odp:status_cwu_odp")->item(0)->getAttribute('id_operacji');
    $ewus_odp['potwierdzenie']=$foundXML;
    $elements = $xpath->query("//odp:status_ubezp");
    $ewus_odp['status'] = $elements->item(0)->nodeValue;
    $ewus_odp['data']=date('Y-m-d'); 
    return $ewus_odp;
	}    
    }
 catch (Exception $e){
    return $e->faultstring;
    }    
}

?>
